package cn.engage.org.service.impl;

import cn.engage.basic.service.impl.BaseServiceImpl;
import cn.engage.org.domain.Department;
import cn.engage.org.mapper.DepartmentMapper;
import cn.engage.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    public List<Department> DeptTree() {
        // 获取所有数据
        List<Department> list = departmentMapper.findAll();
        // 定义一个map来储存父级部门
        Map<Long, Department> parent = list.stream().collect(Collectors.toMap(Department::getId, e -> e));

        // 等同于上面那行代码
//        Map<Long, Department> parent = new HashMap<>();
//        for (Department department : list) {
//            parent.put(department.getId(),department);
//        }

        // 定义一个空集合
        List<Department> departments = new ArrayList<>();
        // 遍历所有数据
        for (Department department : list) {
            // 如果没有parentId就是最大级别部门
            if (department.getParentId() == null){
                departments.add(department);
                // 找到自己的父级部门
            } else {
                // 通过parentId在map中找到自己的父级部门
                Department dept = parent.get(department.getParentId());
                // 得到当前部门的子级部门children集合
                List<Department> children = dept.getChildren();
                // 将当前子级部门装入父级的childre集合里面
                children.add(department);
            }
        }
        return departments;
    }
}
